/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

class ListNode {
    val: number
    next: ListNode | null
    constructor(val?: number, next?: ListNode | null) {
        this.val = (val === undefined ? 0 : val)
        this.next = (next === undefined ? null : next)
    }
}

/**
 * https://leetcode-cn.com/problems/remove-linked-list-elements/
 * 溢出链表元素
 * @param head 
 * @param val 
 */
const removeElements = (head: ListNode | null, val: number): ListNode | null => {
    // 链表为空, 没有元素可以删除
    if (head == null) return null;

    // 1. 使用虚拟头节点
    const dummyHead = new ListNode(0);
    dummyHead.next = head;


    // 2. 遍历链表
    let prev = dummyHead;
    while(head !== null) {
        if (head.val === val) {
            // 让前一个的next指向当前的next, 就能移除节点head
            // head继续指向下一个, prev不变
            head = prev.next = head.next;

        } else {   
            // 保存前一个节点
            prev = head;

            // 指向下一个节点 
            head = head.next;
        }
    }
    
    return dummyHead.next;
};

export {}